import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
const loader = new GLTFLoader()
const model  = new THREE.Group()
model.position.set(0,0,0)
model.name = '全部'
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath( '/glb/draco/' );
loader.setDRACOLoader( dracoLoader );
const textureCube = new THREE.CubeTextureLoader()
    .setPath('/glb/环境贴图0/')
    .load(['px.jpg', 'nx.jpg', 'py.jpg', 'ny.jpg', 'pz.jpg', 'nz.jpg']);
    const material = new THREE.MeshStandardMaterial({
      envMap:textureCube // 环境贴图，用于反射
  });
let   gltfDitu;
  loader.load('/glb/标注.glb',(gltf)=>{
    // console.log('gltf',gltf);
    gltfDitu =  gltf.scene
    gltfDitu.scale.set(2,2,2)
    gltfDitu.rotateX(Math.PI/2)
    gltf.scene.traverse( (child)=> {
      if (child.isMesh) {
        // //模型阴影
        child.castShadow = true;
        child.material.emissive = new THREE.Color('#ffffff'); // 绿色自发光
        child.material.emissiveIntensity = 1; // 调整强度
        child.material.emissiveMap = child.material.map;
      }
    });
  })
  let   gltfYujing;
  loader.load('/glb/预警.glb',(gltf)=>{
    // console.log('gltf',gltf);
    gltfYujing =  gltf.scene
    // gltfYujing.scale.set(2,2,2)
    // gltfYujing.rotateX(Math.PI/2)
    gltf.scene.traverse( (child) =>{
      if (child.isMesh) {
        // //模型阴影
        child.castShadow = true;
        child.material.emissive = new THREE.Color('#ffffff'); // 绿色自发光
        child.material.emissiveIntensity = 1.6; // 调整强度
        child.material.emissiveMap = child.material.map;
      }
    });
  })
  loader.load('/glb/10-12.glb',(gltf)=>{ 
      gltf.scene.name = "模型文件"
      model.add(gltf.scene) // 我的代码
   })
const texLoader = new THREE.TextureLoader();
const texWangerLoader = texLoader.load(require("@/views/witness/components/Object3D/canvas/告警.png"));
const texWangerLoaderBG  =  texLoader.load(require("@/views/witness/components/Object3D/canvas/形状结合@2x.png"));
// const GeoWangerBG = new THREE.PlaneGeometry(6, 2);
// const matWanger = new THREE.MeshBasicMaterial({
//   map: texWangerLoader,
//   transparent: true,
//   // color: 0xff0000,
//   side: THREE.DoubleSide
//   // alphaMap:new THREE.Color('#fff')
// });
// const matWangerBG = new THREE.MeshBasicMaterial({
//   map: texWangerLoaderBG,
//   transparent: true,
//   // color: 0xff0000,
//   side: THREE.DoubleSide
//   // alphaMap:new THREE.Color('#fff')
// });
 // material.emissive = new THREE.Color('#0885d4'); // 绿色自发光
    // material.emissiveIntensity = 0.5; // 调整强度
    // texture.flipY = false;//是否翻转纹理贴图 引入的是false three默认的是,引入贴图需要注意
      //  gltf.scene.traverse(function(obj) {
      //   if (obj.isMesh) {//判断是否是网格模型
      //   }
      //   });
      //  const  gltf.scene.getObjectByName('10F')
      // console.log('gltf',gltf);
      // color:'#fff', // 材质颜色，对于透明材质，这通常影响反射颜色
      // emissive: 0x000000, // 自发光颜色，初始设置为黑色
      // emissiveIntensity: 0.1, // 自发光强度，初始为0
      // metalness: 0, // 金属度，对于玻璃应设置为0
      // roughness: 0.05, // 粗糙度，较低的值产生更光滑的反射
      // transparency: 0.9, // 透明度，接近1表示几乎完全透明
      // opacity: 0.2, // 透明度（与transparency类似，但用于旧版Three.js）
      // side: THREE.DoubleSide, // 渲染材质的双面

// 创建精灵模型
const spriteMaterialWangerBG = new THREE.SpriteMaterial({
  map: texWangerLoaderBG,
  color: 0xffffff,  // 精灵的颜色（可选）
  transparent: true  // 如果图像有透明部分，启用透明度
});
const spriteMaterialWanger = new THREE.SpriteMaterial({
  map: texWangerLoader,
  color: 0xffffff,  // 精灵的颜色（可选）
  transparent: true,  // 如果图像有透明部分，启用透明度
  side: THREE.DoubleSide,
});
export const meshWanger = new THREE.Sprite(spriteMaterialWanger);
meshWanger.scale.set(1, 1, 1);
export const meshWangerBG = new THREE.Sprite(spriteMaterialWangerBG);
export {
  gltfDitu,
  gltfYujing
}


 function loadModel (modelPath){
    return new Promise((resolve,reject)=>{
      let progressTotal = 0;
      const onLoad = (gltf) => {
        resolve(gltf.scene);
      };
      const onProgress = (xhr) => {
        progressTotal = xhr.loaded / xhr.total;
        console.log(`Loading ${modelPath}: ${Math.floor(progressTotal * 100)}%`);
        updateProgressBar(); // 更新进度条
      };
      const onError = (error) => {
        reject(error);
      };
      loader.load(modelPath, onLoad, onProgress, onError);
    })
}
// 定义要加载的模型路径
const models = [
  '/glb/标注.glb',
  '/glb/预警.glb',
  '/glb/10-12.glb'
 ]
const totalModels = models.length;
let loadPromises;
// 获取进度条元素
  const progressBar = document.getElementById('progress')
  console.log('progressBar',progressBar);
  
function updateProgressBar() {
  const currentProgress = Array.from(loadPromises).reduce((acc, promise) => {
    if (promise.progress !== undefined) {
      acc += promise.progress / totalModels;
    }
    return acc;
  }, 0);

  progressBar.style.width = `${currentProgress * 100}%`;
  if (currentProgress >= 1) {
    progressBar.parentElement.style.display = 'none'; // 隐藏进度条
  }
}

 // 主函数：加载所有模型
 async function loadAllModels() {
  // 开始加载
  try {
    loadPromises = models.map((modelPath, index) => {
      return loadModel(modelPath).then(model => {
        model.position.set(Math.random() * 10 - 5, 0, Math.random() * 10 - 5); // 随机位置
        scene.add(model);
        return model;
      });
    });

    await Promise.all(loadPromises);
    console.log('All models loaded');
  } catch (error) {
    console.error('Error loading models:', error);
  }
}
// default loadAllModels();


function getModelDimensions(object) {
    // 创建一个 Box3 对象来计算模型的边界框
    const box = new THREE.Box3().setFromObject(object);

    // 获取边界框的尺寸
    const size = new THREE.Vector3();
    box.getSize(size);

    // 返回宽度和高度
    return {
      width: size.x,   // 模型在 x 轴上的宽度
      height: size.y,  // 模型在 y 轴上的高度
      depth: size.z,   // 模型在 z 轴上的深度
      totalLength: Math.sqrt(size.x * size.x + size.y * size.y + size.z * size.z) // 对角线长度
    };
  }
  // 隐藏进度条  加载完成后需要隐藏进度条
  // document.getElementById('container').style.display = 'none';
  // function getOnProgress (xhr) {
  //   const percent = xhr.loaded / xhr.total;
  //   const percentDiv = {}
  //   // percentDiv.style.width = percent*400 + 'px';
  //   // percentDiv.style.textIndent = percent*400 + 5 + 'px';
  //   // percentDiv.innerHTML = Math.floor(percent*100) + '%';
  //  }
export default model;